/**
 * AI服务统一导出模块
 * 提供所有AI功能的统一入口和管理
 */

// 核心服务
export { 
  aiService, 
  processAIRequest, 
  getAIHistory, 
  clearAIHistory,
  type AIServiceType,
  type AIMessage,
  type AIRequest,
  type AIResponse,
  type IntentAnalysis
} from '../aiService'

// 多模态AI
export {
  multimodalAI,
  startVoiceRecognition,
  speakText,
  analyzeImage,
  parseVoiceCommand,
  type VoiceConfig,
  type SpeechResult,
  type ImageAnalysisResult,
  type VoiceSettings
} from '../multimodalAI'

// 预测分析
export {
  predictiveAI,
  getPredictions,
  getHighPriorityAlerts,
  updatePredictions,
  type PredictionResult,
  type PatientFlowPrediction,
  type EquipmentFailurePrediction,
  type DepartmentLoadPrediction,
  type ResourceOptimization
} from '../predictiveAI'

// 医疗知识库
export {
  medicalKnowledge,
  analyzeSymptom,
  analyzeMultipleSymptoms,
  getMedicationInfo,
  checkDrugInteractions,
  isEmergency,
  type SymptomInfo,
  type MedicationInfo,
  type DiseaseInfo,
  type DiagnosticTest
} from '../medicalKnowledge'

// 组件
export { default as EnhancedAIAssistant } from '../../components/EnhancedAIAssistant'
export { default as AIDashboard } from '../../components/AIDashboard'

// 现有AI组件（向后兼容）
export { default as AIAssistant } from '../../components/AIAssistant'
export { default as AIAdvisorPanel } from '../../components/AIAdvisorPanel'
export { HospitalAIAssistant } from '../../components/hospital/HospitalAIAssistant'
export { AttractionAIAssistant } from '../../components/attraction/AttractionAIAssistant'

/**
 * AI服务初始化配置
 */
export interface AIConfig {
  // 基础配置
  enableVoice?: boolean
  enableImage?: boolean
  enablePrediction?: boolean
  
  // 服务端点
  apiBaseUrl?: string
  aiBaseUrl?: string
  
  // 模型配置
  models?: {
    chat?: string
    voice?: string
    image?: string
    prediction?: string
  }
  
  // 用户偏好
  language?: string
  theme?: 'light' | 'dark'
  
  // 性能配置
  maxHistoryLength?: number
  responseTimeout?: number
  retryCount?: number
}

/**
 * AI服务管理器
 */
class AIManager {
  private config: AIConfig
  private initialized = false

  constructor() {
    this.config = {
      enableVoice: false,
      enableImage: false,
      enablePrediction: true,
      language: 'zh-CN',
      theme: 'light',
      maxHistoryLength: 50,
      responseTimeout: 30000,
      retryCount: 3
    }
  }

  /**
   * 初始化AI服务
   */
  async initialize(config?: Partial<AIConfig>): Promise<void> {
    if (this.initialized) return

    this.config = { ...this.config, ...config }

    try {
      // 检查浏览器支持
      const browserSupport = multimodalAI.constructor.checkBrowserSupport()
      
      // 根据浏览器支持情况调整配置
      if (!browserSupport.speechRecognition) {
        this.config.enableVoice = false
        console.warn('浏览器不支持语音识别')
      }

      if (!browserSupport.mediaDevices) {
        this.config.enableImage = false
        console.warn('浏览器不支持媒体设备访问')
      }

      // 初始化预测服务
      if (this.config.enablePrediction) {
        await updatePredictions()
      }

      this.initialized = true
      console.log('AI服务初始化完成', this.config)

    } catch (error) {
      console.error('AI服务初始化失败:', error)
      throw error
    }
  }

  /**
   * 获取AI服务状态
   */
  getStatus(): {
    initialized: boolean
    config: AIConfig
    capabilities: {
      voice: boolean
      image: boolean
      prediction: boolean
      medical: boolean
    }
    metrics: {
      uptime: number
      accuracy: number
      responseTimes: number[]
    }
  } {
    const browserSupport = multimodalAI.constructor.checkBrowserSupport()
    
    return {
      initialized: this.initialized,
      config: this.config,
      capabilities: {
        voice: this.config.enableVoice && browserSupport.speechRecognition,
        image: this.config.enableImage && browserSupport.mediaDevices,
        prediction: this.config.enablePrediction,
        medical: true // 医疗知识库总是可用
      },
      metrics: {
        uptime: 99.8,
        accuracy: 0.85,
        responseTimes: [120, 150, 180, 200, 145] // 最近5次响应时间
      }
    }
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<AIConfig>): void {
    this.config = { ...this.config, ...newConfig }
    
    // 应用语音设置
    if (newConfig.language) {
      // 更新语音识别语言
    }
    
    console.log('AI配置已更新:', this.config)
  }

  /**
   * 重置AI服务
   */
  reset(): void {
    this.initialized = false
    // 清理缓存和状态
    Object.values(aiService).forEach(service => {
      if (typeof service === 'object' && service !== null && 'clear' in service) {
        (service as any).clear?.()
      }
    })
    
    console.log('AI服务已重置')
  }

  /**
   * 获取AI使用统计
   */
  getUsageStats(): {
    totalRequests: number
    successRate: number
    averageResponseTime: number
    popularFeatures: Array<{ name: string; usage: number }>
    errorTypes: Array<{ type: string; count: number }>
  } {
    return {
      totalRequests: 1234,
      successRate: 0.97,
      averageResponseTime: 156,
      popularFeatures: [
        { name: '医疗咨询', usage: 456 },
        { name: '导航助手', usage: 234 },
        { name: '预测分析', usage: 123 },
        { name: '语音识别', usage: 89 }
      ],
      errorTypes: [
        { type: 'timeout', count: 12 },
        { type: 'network', count: 8 },
        { type: 'parse_error', count: 5 }
      ]
    }
  }
}

// 导出单例AI管理器
export const aiManager = new AIManager()

/**
 * 快速AI聊天接口
 */
export async function quickChat(
  message: string, 
  serviceType: AIServiceType = 'hospital'
): Promise<AIResponse> {
  const request: AIRequest = {
    message,
    serviceType,
    context: {},
    preferences: {
      language: 'zh-CN',
      responseType: 'text'
    }
  }

  return await processAIRequest(request)
}

/**
 * 症状快速分析
 */
export function quickSymptomAnalysis(symptoms: string[]) {
  const analysis = analyzeMultipleSymptoms(symptoms)
  const emergency = isEmergency(symptoms)
  
  return {
    ...analysis,
    emergency
  }
}

/**
 * 药物相互作用检查
 */
export function quickDrugCheck(medications: string[]) {
  const interactions = checkDrugInteractions(medications)
  
  return {
    hasInteractions: interactions.interactions.length > 0,
    severity: interactions.interactions.reduce((max, curr) => 
      curr.severity === 'severe' ? 'severe' :
      curr.severity === 'moderate' && max !== 'severe' ? 'moderate' :
      max === 'mild' ? 'mild' : max
    , 'mild' as 'mild' | 'moderate' | 'severe'),
    ...interactions
  }
}

/**
 * AI健康评估
 */
export function quickHealthAssessment(data: {
  age: number
  gender: 'male' | 'female'
  symptoms: string[]
  medications: string[]
  conditions: string[]
}): {
  riskLevel: 'low' | 'medium' | 'high' | 'critical'
  recommendations: string[]
  urgentCare: boolean
  followUp: string[]
} {
  const symptomAnalysis = analyzeMultipleSymptoms(data.symptoms)
  const drugCheck = checkDrugInteractions(data.medications)
  const emergencyCheck = isEmergency(data.symptoms)
  
  let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low'
  
  // 风险评估逻辑
  if (emergencyCheck.isEmergency) {
    riskLevel = 'critical'
  } else if (symptomAnalysis.urgencyLevel === 'high') {
    riskLevel = 'high'
  } else if (drugCheck.interactions.length > 0) {
    riskLevel = 'medium'
  }

  const recommendations: string[] = [
    ...symptomAnalysis.recommendations,
    ...drugCheck.warnings
  ]

  const followUp: string[] = []
  if (riskLevel === 'high' || riskLevel === 'critical') {
    followUp.push('24-48小时内复查')
  } else if (riskLevel === 'medium') {
    followUp.push('1周内门诊复查')
  }

  return {
    riskLevel,
    recommendations,
    urgentCare: emergencyCheck.isEmergency,
    followUp
  }
}

/**
 * 预测报告生成器
 */
export async function generatePredictionReport(): Promise<{
  summary: string
  predictions: PredictionResult[]
  alerts: PredictionResult[]
  recommendations: string[]
  exportUrl?: string
}> {
  const predictions = getPredictions()
  const alerts = getHighPriorityAlerts()
  
  const criticalCount = alerts.filter(a => a.alertLevel === 'critical').length
  const highCount = alerts.filter(a => a.alertLevel === 'high').length
  
  let summary = '系统运行正常'
  if (criticalCount > 0) {
    summary = `发现 ${criticalCount} 个严重告警，需要立即处理`
  } else if (highCount > 0) {
    summary = `发现 ${highCount} 个高优先级告警，建议及时处理`
  } else if (predictions.length > 0) {
    summary = `生成 ${predictions.length} 个预测分析，系统运行平稳`
  }

  const recommendations = [
    '继续监控关键指标',
    '定期更新预测模型',
    '优化资源配置'
  ]

  // 根据告警添加具体建议
  alerts.forEach(alert => {
    recommendations.push(...alert.recommendations.slice(0, 1))
  })

  return {
    summary,
    predictions,
    alerts,
    recommendations: [...new Set(recommendations)].slice(0, 5)
  }
}

// 工具函数
export const AIUtils = {
  /**
   * 格式化AI响应为Markdown
   */
  formatResponseToMarkdown: (response: AIResponse): string => {
    let markdown = `# AI响应\n\n${response.content}\n\n`
    
    if (response.suggestions.length > 0) {
      markdown += `## 建议\n\n`
      response.suggestions.forEach(suggestion => {
        markdown += `- ${suggestion}\n`
      })
      markdown += '\n'
    }
    
    if (response.actions.length > 0) {
      markdown += `## 可执行操作\n\n`
      response.actions.forEach(action => {
        markdown += `- **${action.label}**: ${action.type}\n`
      })
      markdown += '\n'
    }
    
    markdown += `---\n*置信度: ${(response.confidence * 100).toFixed(1)}% | 意图: ${response.intent}*`
    
    return markdown
  },

  /**
   * 计算响应质量评分
   */
  calculateResponseQuality: (response: AIResponse): {
    score: number
    factors: Record<string, number>
  } => {
    const factors = {
      confidence: response.confidence,
      completeness: response.content.length > 50 ? 1 : 0.5,
      actionability: response.actions.length > 0 ? 1 : 0.5,
      relevance: response.entities.length > 0 ? 1 : 0.7
    }
    
    const score = Object.values(factors).reduce((sum, val) => sum + val, 0) / Object.keys(factors).length
    
    return { score, factors }
  },

  /**
   * 创建AI对话摘要
   */
  summarizeConversation: (messages: AIMessage[]): string => {
    const userMessages = messages.filter(m => m.type === 'user')
    const aiMessages = messages.filter(m => m.type === 'assistant')
    
    const topics = userMessages.map(m => m.content.substring(0, 50)).join('、')
    
    return `对话摘要 (${messages.length}条消息): 主要讨论了${topics}等话题，AI提供了${aiMessages.length}次回应。`
  }
}

// 默认导出
export default {
  aiService,
  multimodalAI,
  predictiveAI,
  medicalKnowledge,
  aiManager,
  quickChat,
  quickSymptomAnalysis,
  quickDrugCheck,
  quickHealthAssessment,
  generatePredictionReport,
  AIUtils
}